package com.example.springcloud.rpc.server.config;

import com.example.springcloud.rpc.api.ErrorResult;
import com.example.springcloud.rpc.api.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 *
 * @author fanhang
 */
@RestControllerAdvice
public class RpcExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(RpcExceptionHandler.class);

    @ExceptionHandler({RpcException.class})
    public ErrorResult businessException(RpcException ex) {
        log.error("RpcException: code:{}, message: {}", ex.getCode(), ex.getMessage());
        return ErrorResult.create(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler({Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResult errorThrowable(Throwable ex) {
        log.error("unkonw exception: ", ex);
        return ErrorResult.create(999, ex.getMessage());
    }
}
